package controllers

import (
	"encoding/json"
	"errors"
	"gitee.com/lzqysoft/ims/libs"
	"gitee.com/lzqysoft/ims/models"
	"github.com/astaxie/beego"
	"strings"
	"time"
)

type MenuController struct {
	CommonController
}

func (c *MenuController) URLMapping() {
	c.Mapping("Get", c.GetAll)
	c.Mapping("Post", c.Post)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("Update", c.Update)
	c.Mapping("Delete", c.Delete)
	c.Mapping("Deletes", c.Deletes)
	c.Mapping("GetMenuList", c.GetMenuList)
}

type menuJson struct {
	Id     string
	Folder string
	Remark string
	Seq    int
	Name   string
	OrgId  string
	Pid    string
	Status int
	Icon   string
}

// @Title Post
// @Description create Menu
// @Param	body		body 	models.Menu	true		"body for Menu content"
// @Success 201 {int} models.Menu
// @Failure 403 body is empty
// @router / [post]
func (c *MenuController) Post() {
	user := c.User
	var v models.Menu
	rdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrToken)
	}
	var m menuJson
	if err = json.Unmarshal(rdata, &m); err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	v.Pid = m.Pid
	v.Seq = m.Seq
	v.Name = m.Name
	v.Status = m.Status
	v.Remark = m.Remark
	v.Icon = m.Icon
	v.Folder = m.Folder
	v.Organization = user.Organization

	//v.Status, _ = strconv.Atoi(sdata["Status"].(string))
	v.Creater = user.Name
	v.Ctime = time.Now()
	v.Updater = v.Creater
	v.Utime = v.Ctime
	v.IsDelete = 0
	v.Id = libs.UUID()
	if err := models.AddMenu(&v, user.Organization); err != nil && err.Error() != "no LastInsertId available" {
		beego.Debug(err)
		c.RetError(ErrDatabase)
	}
	c.Dlog("添加了菜单，id是：", v.Id)
	c.RetSuccess(v.Id)

}

// @Title Get
// @Description get Menu by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.Menu
// @Failure 403 :id is empty
// @router /:id [get]
func (c *MenuController) GetOne() {
	beego.Debug("GetOne")
	// todo
}

// @Title Get All
// @Description get Menu
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.Menu
// @Failure 403
// @router /GetAll [post]
func (c *MenuController) GetAll() {
	//beego.Debug("GetAll")
	user := c.User
	var fields []string
	var sortby []string
	var order []string
	var query map[string]string = make(map[string]string)
	var limit int64 = -1
	var offset int64 = 0
	query["Organization"] = user.Organization.Id
	if v := c.GetString("fields"); v != "" {
		fields = strings.Split(v, ",")
	}
	// limit: 10 (default is 10)

	if v, err := c.GetInt64("limit"); err == nil {
		limit = v
	}
	// offset: 0 (default is 0)

	if v, err := c.GetInt64("offset"); err == nil {
		offset = v
	}
	// sortby: col1,col2

	if v := c.GetString("sortby"); v != "" {
		sortby = strings.Split(v, ",")
	}
	sortby = append(sortby, "Seq")
	// order: desc,asc

	if v := c.GetString("order"); v != "" {
		order = strings.Split(v, ",")
	}
	order = append(order, "asc")
	// query: k:v,k:v

	if v := c.GetString("query"); v != "" {
		for _, cond := range strings.Split(v, ",") {
			kv := strings.SplitN(cond, ":", 2)
			if len(kv) != 2 {
				c.Data["json"] = errors.New("Error: invalid query key/value pair")
				c.ServeJSON()
				return
			}
			k, v := kv[0], kv[1]
			query[k] = v
		}
	}

	l, err := models.GetAllMenus(query, fields, sortby, order, offset, limit)
	if err != nil {
		c.RetError(ErrDatabase)
	}
	//	tree := make(map[string]interface{})
	//	treedata := make([]map[string]interface{}, 0)
	//	org, _ := models.GetOrganizationById(user.OrgId)
	//	tree["org_id"] = user.OrgId
	//	tree["id"] = user.OrgId
	//	tree["expand"] = true
	//	tree["title"] = org.Name
	//	tree["children"] = models.GetDeptTreeByParentIdAndOrgId(0, user.OrgId)
	//	treedata = append(treedata, tree)
	udtree, _ := models.GetMenusTree(user)
	tabledata := make(map[string]interface{})
	tabledata["treedata"] = udtree
	tabledata["tabledata"] = l
	c.RetSuccess(tabledata)
}

// @Title Update
// @Description update the Menu
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.Dept	true		"body for Dept content"
// @Success 200 {object} models.Menu
// @Failure 403 :id is not int
// @router /Update [post]
func (c *MenuController) Update() {
	user := c.User
	rdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrToken)
	}
	var m menuJson
	if err = json.Unmarshal(rdata, &m); err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	v, _ := models.GetMenuById(m.Id)
	v.Name = m.Name
	v.Folder = m.Folder
	v.Icon = m.Icon
	v.Remark = m.Remark
	v.Status = m.Status
	v.Seq = m.Seq
	v.Utime = time.Now()
	v.Updater = user.Name
	v.Pid = m.Pid
	org, _ := models.GetOrganizationById(m.OrgId)
	v.Organization = org
	if err = models.UpdateMenu(v); err != nil {
		beego.Debug(err)
		c.RetError(ErrDatabase)
	}
	c.Dlog("修改栏目", v.Id)
	c.RetSuccess("success")
}

// @Title Delete
// @Description update the Menu
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.Dept	true		"body for Dept content"
// @Success 200 {object} models.Menu
// @Failure 403 :id is not int
// @router /Delete [post]
func (c *MenuController) Delete() {
	user := c.User
	var m menuJson
	rdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	err = json.Unmarshal(rdata, &m)
	if err != nil {
		c.RetError(ErrInputData)
	}

	//	id, err := strconv.ParseInt(sid, 10, 64)
	if rs, err := models.GetMenuByPid(m.Id); err == nil && len(rs) > 0 {
		c.Data["json"] = "GetMenuByPid！"
		c.RetError(ErrPid)
	}
	if err := models.SoftDeleteMenu(m.Id, user.Name); err == nil {
		c.Dlog("删除了系统资源", m.Id)
		c.RetSuccess(m.Id)
	}
	c.RetError(ErrDatabase)
}

// @Title Deletes
// @Description update the Menu
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.Menus	true		"body for Dept content"
// @Success 200 {object} models.Menu
// @Failure 403 :id is not int
// @router /Deletes [post]
func (c *MenuController) Deletes() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.([]interface{})
	for _, value := range sdata {
		id := value.(string)
		err := models.SoftDeleteMenu(id, user.Name)
		if err != nil {
			c.RetError(ErrDatabase)
		}
		c.Dlog("删除了栏目，id为：", id)

	}
	c.RetSuccess("success")
}

// @Title Deletes
// @Description get Menu by org
// @Success 200 {object} models.Menu
// @Failure 403 :database err
// @router /GetMenuList [get]
func (c *MenuController) GetMenuList() {
	user := c.User
	menus, err := models.GetMenuByOrg(user.Organization.Id)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrDatabase)
	}
	c.RetSuccess(menus)
}
